package org.nextive.android.weightapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.nextive.android.weightapp.db.WeightDAO;
import org.nextive.android.weightapp.entities.Weight;
import org.nextive.android.weightapp.utils.AccountsHelper;
import org.nextive.android.weightapp.utils.Utils;
import org.nextive.android.weightapp.utils.WeightCursorAdapter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ShareWeightInfo extends AccountsHelper 
{
	private EditText editTextRecipientEmail;
	private Button buttonSwPickContact;
	private Button buttonSwAccoutEmail;
	private Spinner spinnerShareData;
	private TextView textViewSince;
	private DatePicker datePickerSinceDate;
	private Button buttonShareData;
	
	private WeightDAO weightDAO;
	
	//Constants for pick contact request
	public static final int PICK_CONTACT_REQUEST = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_weight_info);
		
		editTextRecipientEmail = (EditText) findViewById(R.id.editTextRecipientEmail);
		buttonSwPickContact = (Button) findViewById(R.id.buttonSwPickContact);
		buttonSwAccoutEmail = (Button) findViewById(R.id.buttonSwAccoutEmail);
		spinnerShareData = (Spinner) findViewById(R.id.spinnerShareData);
		textViewSince = (TextView) findViewById(R.id.textViewSince);
		datePickerSinceDate = (DatePicker) findViewById(R.id.datePickerSinceDate);
		buttonShareData = (Button) findViewById(R.id.buttonShareData);
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.share_dates, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerShareData.setAdapter(adapter);
		
		weightDAO = new WeightDAO(this);
		weightDAO.open();
		
		spinnerShareData.setOnItemSelectedListener(new OnItemSelectedListener() 
		{
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,int position, long id) 
			{
				updateShareDateSelection(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) 
			{
			}	
		});
		
		buttonSwPickContact.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{
				Intent contactManagerIntent = new Intent(ShareWeightInfo.this, ContactManager.class);
				startActivityForResult(contactManagerIntent,PICK_CONTACT_REQUEST);
			}
		});
		
		buttonSwAccoutEmail.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				selectAccountEmail();
			}
		});
		
		buttonShareData.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{
				shareData();	
			}
		});
		
		SharedPreferences settings = getSharedPreferences(InitialSetup.PREFERENCES_NAME, 0);
        String email = settings.getString(InitialSetup.PREFERENCES_KEY_EMAIL, "");
        editTextRecipientEmail.setText(email);
	}
	
	private void createDefaultRecipientEmailDialog(final String oldEmail, final String newEmail)
	{
		if (!oldEmail.equals(newEmail))
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getResources().getString(R.string.make)+" "+newEmail+" "+getResources().getString(R.string.default_recipient_email).toLowerCase());
			builder.setCancelable(false);
			builder.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() 
			       {
			           public void onClick(DialogInterface dialog, int id) 
			           {   
			        	   SharedPreferences settings = getSharedPreferences(InitialSetup.PREFERENCES_NAME, 0);
			   	    	   SharedPreferences.Editor editor = settings.edit();
			   	    	   editor.putString(InitialSetup.PREFERENCES_KEY_EMAIL, newEmail);
			   	    	   editor.commit();
			           }
			       });
			builder.setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() 
			       {
			           public void onClick(DialogInterface dialog, int id) 
			           {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		switch (requestCode)
		{
			case PICK_CONTACT_REQUEST:
				if (resultCode == RESULT_OK)
				{
					Bundle extras = data.getExtras();
					final String email = extras.getString(ContactManager.EXTRA_KEY_EMAIL);
					createDefaultRecipientEmailDialog(editTextRecipientEmail.getText().toString(), email);
					editTextRecipientEmail.setText(email);
				}
			break;
		}
	}
	
	private void selectAccountEmail()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(ShareWeightInfo.this);
        builder.setTitle(R.string.select_account);
        final String [] accountsArray = new String[getAccounts().size()];
        for (int i=0; i<accountsArray.length; i++)
        {
        	accountsArray[i] = getAccounts().get(i).getName();
        }
        ArrayAdapter<String> accountsDialogAdapter = new ArrayAdapter<String>(this, R.layout.account_menu_item, accountsArray);
        builder.setAdapter(accountsDialogAdapter, new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int item) 
            {
            	createDefaultRecipientEmailDialog(editTextRecipientEmail.getText().toString(), accountsArray[item]);
            	editTextRecipientEmail.setText(accountsArray[item]);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
	}
	
	private void updateShareDateSelection(int position)
	{
		final String[] share_dates = getResources().getStringArray(R.array.share_dates);
		if (share_dates[position].equals("All data"))
		{
			textViewSince.setVisibility(View.GONE);
			datePickerSinceDate.setVisibility(View.GONE);
		}
		else
		{
			textViewSince.setVisibility(View.VISIBLE);
			datePickerSinceDate.setVisibility(View.VISIBLE);
		}
	}
	
	private void shareData()
	{
		String share_dates = (String) spinnerShareData.getSelectedItem();
		Cursor cursor;
		String noDataFound = null;
		if (share_dates.equals("All data"))
		{
			cursor = weightDAO.findAll();
			noDataFound = getResources().getString(R.string.no_weight_data_found);
		}
		else
		{
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_MONTH, datePickerSinceDate.getDayOfMonth());
			calendar.set(Calendar.MONTH, datePickerSinceDate.getMonth());
			calendar.set(Calendar.YEAR, datePickerSinceDate.getYear());
			SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
			cursor = weightDAO.findSinceDate(date.format(calendar.getTime()));
			noDataFound = getResources().getString(R.string.no_weight_data_found_since_selected_date);
		}
		
		if (cursor.getCount()>0)
		{
			WeightCursorAdapter weightCursorAdapter = new WeightCursorAdapter(this, cursor);
			StringBuilder mailBody = new StringBuilder();
			mailBody.append(getResources().getString(R.string.weight_history)+"\n\n");
			
			while(cursor.moveToNext())
			{
				Weight weight = (Weight) weightCursorAdapter.getItem(cursor.getPosition());
				mailBody.append(weight.getDate()+" - "+Utils.getRoundedWeight(this, weight.getWeight())+"\n");
			}
			final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("plain/text");
			emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ editTextRecipientEmail.getText().toString()});
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.weight_history));
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailBody.toString());
			startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.send_email)));
			cursor.close();
		}
		else
		{
			Toast.makeText(this, noDataFound, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	protected void onDestroy() 
	{
		weightDAO.close();
		super.onDestroy();
	}
}
